document.addEventListener("DOMContentLoaded", function () {
    // JSON格式化工具功能
    const jsonInput = document.getElementById("jsonInput");
    const jsonOutput = document.getElementById("jsonOutput");
    const jsonError = document.getElementById("jsonError");

    // 初始化CodeMirror编辑器
    const codeEditor = CodeMirror(document.getElementById("codeEditor"), {
        lineNumbers: true,
        theme: "dracula",
        mode: "htmlmixed",
        lineWrapping: true,
        indentUnit: 4,
        tabSize: 4,
        extraKeys: {
            "Ctrl-Space": "autocomplete",
            "Ctrl-Enter": runCode,
        },
    });

    const outputFrame = document.getElementById("outputFrame");
    const languageSelect = document.getElementById("languageSelect");

    // 设置编辑器初始内容
    codeEditor.setValue(`<!DOCTYPE html>
<html>
<head>
    <title>我的网页</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
        }
        h1 {
            color: #333;
        }
    </style>
</head>
<body>
    <h1>欢迎使用在线代码编辑器</h1>
    <p>尝试编辑HTML/CSS/JavaScript代码并点击运行按钮查看结果。</p>
    
    <script>
        document.querySelector('h1').addEventListener('click', function() {
            alert('您点击了标题!');
        });
    </script>
</body>
</html>`);

    // 语言选择变化时更新编辑器模式
    languageSelect.addEventListener("change", function () {
        switch (this.value) {
            case "html":
                codeEditor.setOption("mode", "htmlmixed");
                break;
            case "css":
                codeEditor.setOption("mode", "css");
                break;
            case "javascript":
                codeEditor.setOption("mode", "javascript");
                break;
            case "python":
                codeEditor.setOption("mode", "python");
                break;
            case "php":
                codeEditor.setOption("mode", "php");
                break;
        }
    });

    // 运行代码
    document.getElementById("runCode").addEventListener("click", runCode);

    function runCode() {
        const code = codeEditor.getValue();
        const lang = languageSelect.value;

        try {
            if (lang === "html") {
                outputFrame.innerHTML = code;
            } else if (lang === "javascript") {
                outputFrame.innerHTML = "<script>" + code + "</script>";
            } else {
                outputFrame.textContent = "运行结果: " + code;
            }
        } catch (error) {
            outputFrame.textContent = "错误: " + error.message;
        }
    }

    // 清空代码编辑器
    document.getElementById("clearCode").addEventListener("click", function () {
        if (confirm("确定要清空编辑器内容吗？")) {
            codeEditor.setValue("");
            outputFrame.innerHTML = "";
        }
    });

    // 保存代码
    document.getElementById("saveCode").addEventListener("click", function () {
        const code = codeEditor.getValue();
        const lang = languageSelect.value;
        const blob = new Blob([code], { type: "text/plain" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `code.${lang}`;
        a.click();
        URL.revokeObjectURL(url);
    });

    // 新建文件
    document.getElementById("newFile").addEventListener("click", function () {
        if (confirm("确定要创建新文件吗？当前内容将丢失。")) {
            codeEditor.setValue("");
            outputFrame.innerHTML = "";
        }
    });

    // 下载代码
    document
        .getElementById("downloadCode")
        .addEventListener("click", function () {
            document.getElementById("saveCode").click();
        });

    // JSON格式化功能
    document
        .getElementById("formatJson")
        .addEventListener("click", function () {
            try {
                const jsonObj = JSON.parse(jsonInput.value);
                jsonOutput.textContent = JSON.stringify(jsonObj, null, 4);
                hideError(jsonError);
                hljs.highlightElement(jsonOutput);
            } catch (error) {
                showError(jsonError, "JSON格式错误: " + error.message);
            }
        });

    // JSON压缩功能
    document
        .getElementById("minifyJson")
        .addEventListener("click", function () {
            try {
                const jsonObj = JSON.parse(jsonInput.value);
                jsonOutput.textContent = JSON.stringify(jsonObj);
                hideError(jsonError);
            } catch (error) {
                showError(jsonError, "JSON格式错误: " + error.message);
            }
        });

    // JSON验证功能
    document
        .getElementById("validateJson")
        .addEventListener("click", function () {
            try {
                JSON.parse(jsonInput.value);
                showError(jsonError, "JSON格式正确", "success");
            } catch (error) {
                showError(jsonError, "JSON格式错误: " + error.message);
            }
        });

    // JSON转XML功能
    document.getElementById("jsonToXml").addEventListener("click", function () {
        try {
            const jsonObj = JSON.parse(jsonInput.value);
            jsonOutput.textContent = jsonToXml(jsonObj);
            hideError(jsonError);
        } catch (error) {
            showError(jsonError, "JSON格式错误: " + error.message);
        }
    });

    // 清空JSON
    document.getElementById("clearJson").addEventListener("click", function () {
        jsonInput.value = "";
        jsonOutput.textContent = "";
        hideError(jsonError);
    });

    // 复制JSON结果
    document.getElementById("copyJson").addEventListener("click", function () {
        navigator.clipboard
            .writeText(jsonOutput.textContent)
            .then(() => alert("已复制到剪贴板"))
            .catch((err) => alert("复制失败: " + err));
    });

    // 下载JSON
    document
        .getElementById("downloadJson")
        .addEventListener("click", function () {
            const blob = new Blob([jsonOutput.textContent], {
                type: "application/json",
            });
            const url = URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = "data.json";
            a.click();
            URL.revokeObjectURL(url);
        });

    // JSON转XML辅助函数
    function jsonToXml(obj, nodeName = "root") {
        let xml = "";

        if (Array.isArray(obj)) {
            obj.forEach((item, index) => {
                xml += jsonToXml(item, nodeName + "_" + index);
            });
        } else if (typeof obj === "object" && obj !== null) {
            xml += "<" + nodeName + ">";
            for (const key in obj) {
                if (obj.hasOwnProperty(key)) {
                    xml += jsonToXml(obj[key], key);
                }
            }
            xml += "</" + nodeName + ">";
        } else {
            xml +=
                "<" + nodeName + ">" + obj.toString() + "</" + nodeName + ">";
        }

        return xml;
    }

    // 显示错误信息
    function showError(element, message, type = "error") {
        element.textContent = message;
        element.style.display = "block";
        element.className = "error-message " + type;
    }

    // 隐藏错误信息
    function hideError(element) {
        element.textContent = "";
        element.style.display = "none";
    }
});
